package com.neoz.demo.javabasic;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;

import com.neoz.demo.javabasic.util.CmdUtil;

public class SimpleSocket {

	public static class Server implements Runnable {
		public void run() {
			try {
				ServerSocket s = null;
				s = new ServerSocket(10086);
				while (true) {
					Socket s1 = s.accept();
					OutputStream s1out = s1.getOutputStream();
					BufferedWriter bw = new BufferedWriter(
							new OutputStreamWriter(s1out));
					bw.write("You are at SimpleSocket!\n");
					bw.close();
					s1.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static class Client {
		public void run() {
			try {
				Socket s1 = new Socket("127.0.0.1", 10086);
				BufferedReader br = new BufferedReader(new InputStreamReader(
						s1.getInputStream()));
				CmdUtil.print("Client received [" + br.readLine() + "]");
				br.close();
				s1.close();
			} catch (ConnectException connExc) {
				CmdUtil.print("Could not connect to the server.");
			} catch (IOException e) {
			}
		}
	}

	public static void main(String[] args) throws IOException {
		CmdUtil.printTitle("Start socket server at port 10086");
		Thread t = new Thread(new Server());
		t.start();
		new Client().run();
	}

}
